<template>
  <div class="public">
    <baidu-map @ready="getLocation"></baidu-map>
    <div>{{ address }}</div>
    <van-index-bar :index-list="cityList">
      <div v-for="(item, idx) in renderCityList" :key="idx">
        <van-index-anchor :index="item.key" />
        <van-cell v-for="(val, i) in item.citys" :key="i" :title="val.name" />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import { getCityList } from "@/api";
import { cPinyin } from "@/utils";
import { mapState, mapMutations } from 'vuex'
export default {
  name: "TestBaiDu",
  data() {
    return {
      cityList: [],
      renderCityList: []
    };
  },
  computed: {
    ...mapState(['address'])
  },
  created() {
    this.getCity();

    this.CHANGE_ADDRESS('定位中...')
  },
  methods: {
    ...mapMutations(['CHANGE_ADDRESS']),
    // 获取城市列表
    getCity() {
      getCityList().then((res) => {
        // 给所有字段 加一个拼音首字母
        let cityList = res.data.map((item) => {
          return {
            ...item,
            py: cPinyin(item.name.slice(0,1)),
          };
        });

        // 取出所有拼音做去重
        let newArr = Array.from(new Set(cityList.map(item => item.py)))

        //  给数组做排序
        this.cityList = newArr.sort((a, b) => {
          return a.charCodeAt(0) - b.charCodeAt(0)
        })

        // 生成需要遍历渲染的数组
        this.renderCityList = this.cityList.map(item => {
          return {
            key: item,
            citys: cityList.filter(val => val.py === item)
          }
        })

      });
    },
    // 定位

    getLocation(map) {
      // 触发定位方法
      const location = new map.BMap.Geolocation()

      // 获取定位信息
      location.getCurrentPosition((r) => {
        // r：定位之后的位置信息
        this.CHANGE_ADDRESS(r.address.city)
      }) 
    },
  },
};
</script>